package com.jimmyhsu.ecnudaowei.coursetable;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.jimmyhsu.ecnudaowei.Bean.TaskActivity;
import com.jimmyhsu.ecnudaowei.Db.UserDbHelper;
import com.jimmyhsu.ecnudaowei.R;
import com.jimmyhsu.ecnudaowei.coursetable.view.CourseTableLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by jimmyhsu on 2017/3/12.
 */

public class CourseTableFragment extends Fragment implements CourseTableLayout.OnCourseClickedListner {

    public static final String SP_COURSE = "sp_course";
    public static final String SP_KEY_SYNCED = "sp_key_synced";
    public static final String ACTION_TO_SYNC = "com.jimmyhsu.ecnudaowei.broadcast.action_to_sync";
    public static final String[] COURSE_TIME_START_POINT = new String[]{
            "8:00", "8:45", "10:00", "10:45", "13:00", "13:45", "15:00", "15:45", "18:00", "18:45"
    };
    public static final String[] COURSE_TIME_END_POINT = new String[]{
            "8:45", "9:30", "10:45", "11:30", "13:45", "14:30", "15:45", "16:30", "18:45", "19:30"
    };
    private int mMaxWeek = 19;
    private int mWeek = 1;

    public int getMaxWeek() {
        return mMaxWeek;
    }

    private Unbinder mUnbinder;

    @BindView(R.id.id_ct_course)
    CourseTableLayout mCourseTable;

    @BindView(R.id.id_ct_guide)
    RelativeLayout mGuideView;

    @BindView(R.id.id_ct_bg)
    View mBgView;

    private List<TaskActivity> mTasks;
    private UserDbHelper mDbHelper = UserDbHelper.getInstance(getContext());
    private TaskActivity mCurrCourse;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_course_table, container, false);
        mUnbinder = ButterKnife.bind(this, view);
        getActivity().setTitle(getString(R.string.course_table));
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SharedPreferences sp = getContext().getSharedPreferences(SP_COURSE, Context.MODE_PRIVATE);
        boolean hasSynced = sp.getBoolean(SP_KEY_SYNCED, false);
        if (hasSynced) {
            mGuideView.setVisibility(View.GONE);
            mCourseTable.setVisibility(View.VISIBLE);
            getTasks();
            mCourseTable.setCourses(mTasks);
            mCourseTable.setOnCourseClickListner(this);
        } else {
            resync();
        }
    }

    public void resync() {
        mGuideView.setVisibility(View.VISIBLE);
        mCourseTable.setVisibility(View.GONE);
    }

    @Nullable
    @OnClick(R.id.id_ct_sync)
    void sync() {
        Intent intent = new Intent().setAction(ACTION_TO_SYNC);
        getContext().sendBroadcast(intent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnbinder.unbind();
    }

    public void getTasks() {
        mTasks = new ArrayList<>();
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from " + TaskActivity.TB_COURSE, null);
        while (cursor.moveToNext()) {
            TaskActivity course = new TaskActivity(
                    cursor.getInt(cursor.getColumnIndex("_id")),
                    cursor.getString(cursor.getColumnIndex(TaskActivity.COL_COURSE_ID)),
                    cursor.getString(cursor.getColumnIndex(TaskActivity.COL_COURSE_NAME)),
                    cursor.getString(cursor.getColumnIndex(TaskActivity.COL_TEACHER)),
                    cursor.getString(cursor.getColumnIndex(TaskActivity.COL_LOCATION)),
                    cursor.getString(cursor.getColumnIndex(TaskActivity.COL_COURSE_WEEK)),
                    cursor.getInt(cursor.getColumnIndex(TaskActivity.COL_DAY)),
                    cursor.getInt(cursor.getColumnIndex(TaskActivity.COL_NUMBER)),
                    cursor.getInt(cursor.getColumnIndex(TaskActivity.COL_ADD_BY_USER)) == 1);
            course.setDuration(cursor.getInt(cursor.getColumnIndex(TaskActivity.COL_DURATION)));
            mTasks.add(course);
        }
        cursor.close();
        db.close();
    }

    @Override
    public void onClick(View courseView, TaskActivity courseInfo) {
        mCurrCourse = courseInfo;
        CourseDetails details = new CourseDetails(courseInfo.getCourseName(),
                courseInfo.getLocation(),
                parseWeek(courseInfo.getCourseWeek()),
                parseNumber(courseInfo.getDay(), courseInfo.getNumber(), courseInfo.getDuration()),
                parseTime(courseInfo.getNumber(), courseInfo.getDuration()),
                courseInfo.getTeacher());
        EventBus.getDefault().post(details);
    }

    public TaskActivity getCurrCourse() {
        return mCurrCourse;
    }

    private static String parseTime(int number, int duration) {
        return COURSE_TIME_START_POINT[number] + "~" + COURSE_TIME_END_POINT[number + duration - 1] ;
    }

    private static String parseNumber(int day, int beginNumber, int duration) {
        return "周" + CourseTableLayout.NUMBERS[day] + " " + (beginNumber + 1) +
                "~" + (beginNumber + duration) + "节";
    }

    public List<String> getAvailWeek(int day, int num, int duration) {
        return mCourseTable.getAvailWeek(day, num, duration);
    }

    public List<String> getAvailWeek(int day, int num, int duration, TaskActivity except) {
        return mCourseTable.getAvailWeek(day, num, duration, except);
    }

    public static String parseWeek(String rawWeek) {
        StringBuffer sb = new StringBuffer().append("第");
        int start = 0;
        int duration = 0;
        for (int i = 0; i < rawWeek.length(); i++) {
            char c = rawWeek.charAt(i);
            if (c == '1') {
                if (duration == 0) {
                    start = i;
                    duration = 1;
                } else {
                    duration++;
                }
            } else if (c == '0' && duration > 0){
                sb = sb.append(duration == 1 ? start : start + "~" + (start+duration-1)).append(',');
                duration = 0;
                start = i;
            }
        }
        String result = sb.substring(0, sb.length() - 1);
        if (result.length() == 0) {
            return "未知周";
        } else {
            return result + "周";
        }
    }

    public void setWeek(int week) {
        mCourseTable.setCurrentWeek(week);
    }

    public int getWeek() {
        return this.mWeek;
    }

    public void setAlpha(float alpha) {
        mBgView.setAlpha(1 - alpha);
    }

    public void enterEditorMode() {
        mCourseTable.enterEditorMode();
        getActivity().invalidateOptionsMenu();
    }

    public boolean isInEditorMode() {
        return mCourseTable != null && mCourseTable.isInEditorMode();
    }

    public void quitEditorMode(boolean animated) {
        mCourseTable.exitEditorMode(animated);
        getActivity().invalidateOptionsMenu();
    }

    public void refresh() {
        getTasks();
        quitEditorMode(false);
        mCourseTable.setCourses(mTasks);
    }
}
